package com.jn.book.views;

import android.content.Intent;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.jn.book.R;
import com.jn.book.adapter.BooksAdapter;
import com.jn.book.base.BaseActivity;
import com.jn.book.databinding.ActivityBooksBinding;
import com.jn.book.entity.Books;
import com.jn.book.viewmodel.BooksViewModel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class BooksActivity extends BaseActivity<ActivityBooksBinding> {
    private BooksAdapter mAdapter;
    private List<Books.ResultDTO.DataDTO> mList;

    @Override
    public int getLayoutId() {
        return R.layout.activity_books;
    }

    @Override
    public void init() {
        BooksViewModel booksViewModel = new ViewModelProvider(this).get(BooksViewModel.class);
        LiveData<Books> booksLiveData = booksViewModel.getLiveData();
        Intent intent = getIntent();
        String catalog_id = intent.getStringExtra("catalog_id");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mBinding.recyclerView.setLayoutManager(linearLayoutManager);
        mList = new ArrayList<>();
        mAdapter = new BooksAdapter(mList);
        mBinding.recyclerView.setAdapter(mAdapter);
        booksLiveData.observe(this, new Observer<Books>() {
            @Override
            public void onChanged(Books books) {
                mList = books.getResult().getData();
                mAdapter.updateData(mList);
            }
        });
        mAdapter.setOnItemClickListener(new BooksAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Books.ResultDTO.DataDTO book) {
                Intent intent1 = new Intent(BooksActivity.this, BookDetailActivity.class);
                intent1.putExtra("book", (Serializable) book);
                startActivity(intent1);
            }
        });

        booksViewModel.getBooks("39874cea287f683d8ef362984c4de76e", catalog_id);
    }
}